//
//  ProductDetailViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/5/13.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "ProductDetailViewController.h"
#import "SearchData.h"
#import "OneLineWithInfoCell.h"
#import "UITapView.h"
#import "UITapImageView.h"
#import "BrowserViewController.h"

@interface ProductDetailViewController ()

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,retain) NSMutableArray *dataSource;
@property (nonatomic,retain) NSString *doc;
@property (nonatomic,strong) UITapImageView *image;
@property (nonatomic,strong)MWPhoto *photo;
@property (nonatomic,strong)UIBarButtonItem *publish;


@end

@implementation ProductDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    
    self.publish =[[UIBarButtonItem alloc]initWithTitle:@"查看文档" style:UIBarButtonItemStyleDone target:self action:@selector(viewDoc)];
    self.navigationItem.rightBarButtonItem = self.publish;
    
    [self setupViews];
//    [self loadData];
    
}

- (void)viewDoc {
    if ([Tools isEmpty:self.doc]) {
        [Tools showMessageCenter:@"该产品介绍文档不存在！"];
        return;
    }
    BrowserViewController *view = [BrowserViewController new];
    view.title = @"功能介绍";
    view.urlStr = [Tools getResourceFullPath:self.doc];
    [self.navigationController pushViewController:view animated:YES];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//    NSString *picUrl = [NSString stringWithFormat:HTTP_GET_ONE_PRODUCT_PICTURE, HTTP_HOST, [[AccountManager manager]token], self.product_type, self.equip_id];
   
    [self loadData];
}

#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"产品信息";
    self.view.backgroundColor = [UIColor whiteColor];
    
    //适配iOS7uinavigationbar遮挡tableView的问题
    if(IS_IOS7)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    //自定义返回按钮
//    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(onBack)];
//    self.navigationItem.leftBarButtonItem = backBtn;
    
    //表头
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Width/2)];
    self.image = [[UITapImageView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Width/2)];
    self.image.contentMode = UIViewContentModeScaleAspectFit;
    
    __block ProductDetailViewController *tmp = self;
    [self.image addTargetBlock:^(id obj) {
        MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:tmp];
        
        // Set options
        browser.displayActionButton = NO; // Show action button to allow sharing, copying, etc (defaults to YES)
        browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
        browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
        browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
        browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
        browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
        browser.startOnGrid = NO; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
//                browser.wantsFullScreenLayout = YES; // iOS 5 & 6 only: Decide if you want the photo browser full screen, i.e. whether the status bar is affected (defaults to YES)
        
        // Optionally set the current visible photo before displaying
        [browser setCurrentPhotoIndex:1];
        
        // Present
        [tmp.navigationController pushViewController:browser animated:YES];
        
        // Manipulate
        //        [browser showNextPhotoAnimated:YES];
        //        [browser showPreviousPhotoAnimated:YES];
        //        [browser setCurrentPhotoIndex:1];
    }];
    [header addSubview:self.image];
    
//    [self.image sd_setImageWithURL: placeholderImage:nil];
    
    
    //列表
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNav] style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableHeaderView = header;
    [self.view addSubview:self.tableView];
}


- (void)onBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIImage *)croppedImage:(UIImage *)image

{
    if (image)
    {
        CGRect rectMAX = CGRectMake(0, 0, 128, 128);
        
        CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rectMAX);
        
        UIGraphicsBeginImageContext(rectMAX.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextDrawImage(context, rectMAX, subImageRef);
        UIImage *viewImage = [UIImage imageWithCGImage:subImageRef];
        UIGraphicsEndImageContext();
        CGImageRelease(subImageRef);
        return viewImage;
    }
    
    return nil;
    
}

#pragma mark - 加载数据
/**
 *  初始化数据
 */
- (void)initData {
    self.dataSource = nil;
}

/**
 *  加载视图所有的数据
 */
- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:self.product_type forKey:@"product_type"];
    [param setValue:self.equip_id forKey:@"equip_id"];
    
    
    [HttpClient getWithUrl:HTTP_GET_EQUIP_DETAIL token:[[AccountManager manager]token] paramDic:param resultClass:[SearchData class] success:^(SearchData *obj) {
        if (obj.propertyGroups != nil) {
            self.dataSource = [obj.propertyGroups mutableCopy];
            if ([Tools isEmpty:obj.doc]) {
                self.navigationItem.rightBarButtonItem = nil;
            }
            self.doc = obj.doc;
            [self.image sd_setImageWithURL:[Tools getResourceFullPathURL:obj.picture] placeholderImage:nil];
            self.photo = [MWPhoto photoWithURL:[Tools getResourceFullPathURL:obj.picture]];
            
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        CMLog(@"获取产品失败：%@", error);
    }];
}

#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.dataSource != nil) {
        return self.dataSource.count;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.dataSource != nil) {
        PropertyGroupData *data = [self.dataSource objectAtIndex:section];
        if (data.isClosed) {
            return 0;
        }
        return data.properties.count;
    }
    return 0;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dataSource == nil) {
        return nil;
    }
    PropertyGroupData *data = [self.dataSource objectAtIndex:indexPath.section];
    PropertyData *item = [data.properties objectAtIndex:indexPath.row];
    
    static NSString *identifier = @"ProductCell";
    OneLineWithInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[OneLineWithInfoCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    cell.userInteractionEnabled = NO;
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    NSString *info = item.value;
    if (![Tools isEmpty:item.unit]) {
        info = [NSString stringWithFormat:@"%@ (%@)", item.value, item.unit];
    } else {
        info = item.value;
    }
//    [cell setTitleStr:item.name andInfoStr:info andInfoColor:CM_TABLE_INFO_COLOR
//    andInfoAlignment:NSTextAlignmentRight];
    [cell setTitleStr:item.name andInfoStr:item.value andUnitStr:item.unit];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"ProductCell";
    OneLineWithInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[OneLineWithInfoCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    return [cell getHeight];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 2*DEFAULT_SECTION_HEIGHT;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (self.dataSource == nil) {
        return nil;
    }
    PropertyGroupData *data = [self.dataSource objectAtIndex:section];
    UITapView *headView = [[UITapView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 2*DEFAULT_SECTION_HEIGHT)];
    [headView setBgColor:[UIColor whiteColor] andHighLightBgColor:[UIColor whiteColor]];
    [headView addTargetsBlock:^(id obj) {
        data.isClosed = !data.isClosed;
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
    
    UILabel *label;
    label = [UILabel labelSingleLineFontSize:kActionBarFontSize content:data.group];
    label.textColor = CM_ORANGE_COLOR;
    label.x = CELL_PADDING_LEFT;
    label.centerY = headView.height/2;
    [headView addSubview:label];
    
    UIImage *image;
    if (!data.isClosed) {
        image = [UIImage imageNamed:@"select_user_up"];
    }
    else {
        image = [UIImage imageNamed:@"select_user_down"];
    }
    
    UITapImageView *imageView = [[UITapImageView alloc]initWithImage:image];
    imageView.x = kScreen_Width - CELL_PADDING_RIGHT - imageView.size.width;
    imageView.centerY = headView.height/2;
    [headView addSubview:imageView];
    
    return headView;
}

#pragma mark - 图片浏览器代理
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return 1;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    //    if (index < self.photos.count)
    //        return [self.photos objectAtIndex:index];
    return self.photo;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
